#include "acceptor.hpp"

#include <boost/bind.hpp>
#include <boost/asio/placeholders.hpp>
#include <iioservice.hpp>
#include <IConnection.hpp>

#include <iostream>

using namespace boost::asio;

Acceptor::Acceptor(IIOService& ioService)
	: m_acceptor(ioService.getBoostIoService())
{
}

void Acceptor::openBindAndListen(const std::string& address, const std::string& port)
{
	ip::tcp::resolver resolv(m_acceptor.get_io_service());
	ip::tcp::resolver::query qr(address, port);
	ip::tcp::endpoint endp = *resolv.resolve(qr);

	m_acceptor.open(endp.protocol());
	m_acceptor.set_option(ip::tcp::acceptor::reuse_address(true));
	m_acceptor.bind(endp);
	m_acceptor.listen();
}

void Acceptor::asyncAccept(std::shared_ptr<IConnection>& connection, IAcceptorHandler& accept)
{
	m_acceptor.async_accept(*connection->stream().rdbuf(), boost::bind(&IAcceptorHandler::onAccepted, &accept, placeholders::error));
}

Acceptor::~Acceptor()
{
}
